﻿using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;

namespace CARD_INFO
{
    public partial class MainForm : Form
    {
        private bool b_Download = (ConfigurationManager.AppSettings["人员照片下载"] != "0");
        private string PhotoPath = ConfigurationManager.AppSettings["人员照片本地路径"];
        private string FtpString = ConfigurationManager.AppSettings["人员照片FTP服务器"];
        private string FtpUrl;
        private string FtpUser;
        private string FtpPwd;
        Assembly _assembly;
        Stream _imageStream;
        Bitmap DefaultPhoto;

        Thread Search_Thread;

        public class cardinfo
        {
            public string cardno;
            public string rfid;
            public string staffno;
            public string name;
            public string org;
            public string job;
            public string job_lev;
            public string tel;
            public string mobile;
            public Bitmap photo;
            public int status;
        }

        public cardinfo card = new cardinfo();
        

        public MainForm()
        {
            InitializeComponent();
            _assembly = Assembly.GetExecutingAssembly();
            _imageStream = _assembly.GetManifestResourceStream("CARD_INFO.Default.jpg");
            DefaultPhoto = new Bitmap(_imageStream);
            FtpParse(FtpString);
        }

        private void tb_cardno_Leave(object sender, EventArgs e)
        {
            tb_cardno.Focus();
        }

        private void bt_search_Click(object sender, EventArgs e)
        {
            lb_info.Text = "查询中，请稍后";

            //string str_card = Convert.ToString(3504470131, 16);
            //string str = shift_fun3(str_card);

            if (Search_Thread != null)
            {
                Search_Thread.Abort();
            }

            Search_Thread = new Thread(new ParameterizedThreadStart(SearchInfo));
            Search_Thread.IsBackground = true;
            Search_Thread.Start(tb_cardno.Text);

            tb_cardno.Text = "";
        }

        public string shift_fun2(UInt32 data)
        {

            UInt32 data4 = (data << 4) | (data >> 4);
            //UInt32 data2 = ((data4 << 2) & 0xcc) | ((data4 >> 2) & 0x33);

            string str_card = Convert.ToString(data4, 16);
            //data = ((data << 1) & 0xaa) | ((data >> 1) & 0x55);
            //printf("  after shift fun2 data=%x \n", data);
            return str_card;
        }


        public string shift_fun3(string  data)
        {
            int n = data.Length;
            if (n < 8) return data;            

            string str_card = data.Substring(6, 2) + data.Substring(4, 2) + data.Substring(2, 2) + data.Substring(0, 2);              
            return str_card;
        }

        private void SearchInfo(object obj)
        {
            string cardstring = obj as string;
            int t;
            if ((cardstring == null) || (cardstring.Length <= 0))
            {
                card.status = -100;
            }
            else if (!int.TryParse(cardstring, out t))
            {
                card.status = -3;
            }
            else if (cardstring.Length < 5)
            {
                try
                {
                    SqlDataReader reader = DB_SQLServer.ExecuteReader(string.Format("SELECT t.[TagMac],t.[NFC],s.[StaffNo],s.[StaffName],(SELECT [DEPTNAME] FROM [SYS_DEPT] WHERE [SYS_DEPT].[DEPTID] = s.[DeptID]),(SELECT [TYPEJOBNAME] FROM [T_SM_TypeJob] WHERE [T_SM_TypeJob].[TYPEJOBID] = s.[TYPEJOB]),(SELECT [PositionsName] FROM [T_SM_Position] WHERE [T_SM_Position].[PositionsID] = s.[PositionsID]),s.[StaffTel],s.[Mobile],s.[StaffPhotoPath] FROM [T_JC_Tag] t LEFT JOIN [T_SM_Staff] s ON t.[StafffID] = s.[StaffID] WHERE t.[TagMac] = '{0}'", cardstring));
                    if (reader.Read())
                    {
                        card.cardno = reader[0].ToString();
                        card.rfid = reader[1].ToString();
                        card.staffno = reader[2].ToString();
                        card.name = reader[3].ToString();
                        card.org = reader[4].ToString();
                        card.job = reader[5].ToString();
                        card.job_lev = reader[6].ToString();
                        card.tel = reader[7].ToString();
                        card.mobile = reader[8].ToString();
                        card.photo = GetPhoto(reader[9].ToString().Replace('\\', '/'));
                        if (card.staffno.Length > 0)
                        {
                            card.status = 1;
                        }
                        else
                        {
                            card.status = 0;
                        }
                    }
                    else
                    {
                        card.cardno = cardstring;
                        card.status = -1;
                    }
                    reader.Close();
                }
                catch
                {
                    card.status = -4;
                }
                
            }
            else
            {
                try
                {
                    SqlDataReader reader = DB_SQLServer.ExecuteReader(string.Format("SELECT t.[TagMac],t.[NFC],s.[StaffNo],s.[StaffName],(SELECT [DEPTNAME] FROM [SYS_DEPT] WHERE [SYS_DEPT].[DEPTID] = s.[DeptID]),(SELECT [TYPEJOBNAME] FROM [T_SM_TypeJob] WHERE [T_SM_TypeJob].[TYPEJOBID] = s.[TYPEJOB]),(SELECT [PositionsName] FROM [T_SM_Position] WHERE [T_SM_Position].[PositionsID] = s.[PositionsID]),s.[StaffTel],s.[Mobile],s.[StaffPhotoPath] FROM [T_JC_Tag] t LEFT JOIN [T_SM_Staff] s ON t.[StafffID] = s.[StaffID] WHERE t.[NFC] = '{0}'", cardstring));
                    if (reader.Read())
                    {
                        card.cardno = reader[0].ToString();
                        card.rfid = reader[1].ToString();
                        card.staffno = reader[2].ToString();
                        card.name = reader[3].ToString();
                        card.org = reader[4].ToString();
                        card.job = reader[5].ToString();
                        card.job_lev = reader[6].ToString();
                        card.tel = reader[7].ToString();
                        card.mobile = reader[8].ToString();
                        card.photo = GetPhoto(reader[9].ToString().Replace('\\', '/'));
                        if (card.staffno.Length > 0)
                        {
                            card.status = 1;
                        }
                        else
                        {
                            card.status = 0;
                        }
                    }
                    else
                    {
                        card.rfid = cardstring;
                        card.status = -2;
                    }
                    reader.Close();
                }
                catch
                {
                    card.status = -4;
                }
                
            }

            MethodInvoker threadappend = delegate()
            {
                if (card.status == 1)
                {
                    lb_cardno.Text = card.cardno;
                    lb_rfid.Text = card.rfid;
                    lb_staffno.Text = card.staffno;
                    lb_name.Text = card.name;
                    lb_org.Text = card.org;
                    lb_job.Text = card.job;
                    lb_job_lev.Text = card.job_lev;
                    lb_tel.Text = card.tel;
                    lb_mobile.Text = card.mobile;
                    pb_photo.Image = card.photo;
                    lb_info.Text = "状态正常";
                }
                else if (card.status == 0)
                {
                    lb_cardno.Text = card.cardno;
                    lb_rfid.Text = card.rfid;
                    lb_staffno.Text = "";
                    lb_name.Text = "";
                    lb_org.Text = "";
                    lb_job.Text = "";
                    lb_job_lev.Text = "";
                    lb_tel.Text = "";
                    lb_mobile.Text = "";
                    pb_photo.Image = DefaultPhoto;
                    lb_info.Text = "此卡未使用";
                }
                else if (card.status == -1)
                {
                    lb_cardno.Text = card.cardno;
                    lb_rfid.Text = "";
                    lb_staffno.Text = "";
                    lb_name.Text = "";
                    lb_org.Text = "";
                    lb_job.Text = "";
                    lb_job_lev.Text = "";
                    lb_tel.Text = "";
                    lb_mobile.Text = "";
                    pb_photo.Image = DefaultPhoto;
                    lb_info.Text = "此卡未录入";
                }
                else if (card.status == -2)
                {
                    lb_cardno.Text = "";
                    lb_rfid.Text = card.rfid;
                    lb_staffno.Text = "";
                    lb_name.Text = "";
                    lb_org.Text = "";
                    lb_job.Text = "";
                    lb_job_lev.Text = "";
                    lb_tel.Text = "";
                    lb_mobile.Text = "";
                    pb_photo.Image = DefaultPhoto;
                    lb_info.Text = "此卡未录入";
                }
                else if (card.status == -3)
                {
                    lb_cardno.Text = "";
                    lb_rfid.Text = "";
                    lb_staffno.Text = "";
                    lb_name.Text = "";
                    lb_org.Text = "";
                    lb_job.Text = "";
                    lb_job_lev.Text = "";
                    lb_tel.Text = "";
                    lb_mobile.Text = "";
                    pb_photo.Image = DefaultPhoto;
                    lb_info.Text = "卡号错误";
                }
                else if (card.status == -4)
                {
                    lb_cardno.Text = "";
                    lb_rfid.Text = "";
                    lb_staffno.Text = "";
                    lb_name.Text = "";
                    lb_org.Text = "";
                    lb_job.Text = "";
                    lb_job_lev.Text = "";
                    lb_tel.Text = "";
                    lb_mobile.Text = "";
                    pb_photo.Image = DefaultPhoto;
                    lb_info.Text = "数据库连接失败";
                }
                else if (card.status == -100)
                {
                    lb_cardno.Text = "";
                    lb_rfid.Text = "";
                    lb_staffno.Text = "";
                    lb_name.Text = "";
                    lb_org.Text = "";
                    lb_job.Text = "";
                    lb_job_lev.Text = "";
                    lb_tel.Text = "";
                    lb_mobile.Text = "";
                    pb_photo.Image = DefaultPhoto;
                    lb_info.Text = "";
                }

                Search_Thread = null;
            };

            BeginInvoke(threadappend);
        }

        private void FtpParse(string FtpString)
        {
            string[] arrFtpString = FtpString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < arrFtpString.Length; i++)
            {
                if (arrFtpString[i].IndexOf("url=") >= 0)
                {
                    FtpUrl = arrFtpString[i].Substring(4);
                }
                else if (arrFtpString[i].IndexOf("user=") >= 0)
                {
                    FtpUser = arrFtpString[i].Substring(5);
                }
                else if (arrFtpString[i].IndexOf("pwd=") >= 0)
                {
                    FtpPwd = arrFtpString[i].Substring(4);
                }
            }
        }

        private Bitmap GetPhoto(string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                if (fileName.Length <= 0)
                {
                    return DefaultPhoto;
                }
                string path = PhotoPath + fileName;

                if (File.Exists(path))
                {
                    return new Bitmap(path);
                }

                if (!b_Download)
                {
                    return DefaultPhoto;
                }

                string directory = path.Substring(0, path.LastIndexOf('/'));
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpUrl + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = false;
                reqFTP.Credentials = new NetworkCredential(FtpUser, FtpPwd);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);

                if (readCount <= 0)
                {
                    ftpStream.Close();
                    response.Close();
                    return DefaultPhoto;
                }

                FileStream outputStream = new FileStream(path, FileMode.Create);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                response.Close();
                outputStream.Close();
                return new Bitmap(path);
            }
            catch
            {
                return DefaultPhoto;
            }
        }
    }
}
